package com.coke.im.client.stream;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

import com.coke.im.client.exception.MessageException;
import com.coke.im.client.type.ExecStatus;

public class MessageStream extends InputStream {

	private DataInputStream mDataInputStream;

	public MessageStream(InputStream ips) {
		mDataInputStream = new DataInputStream(ips);

	}

	public Message readMessage() throws Exception {

		Message msg = new Message();
		while (true) {
			@SuppressWarnings("deprecation")
			String line = mDataInputStream.readLine();
			
			if (line==null||line.length() == 0) {
				break;
			}
			String[] rlines = line.split(":");
			if (rlines.length == 2) {
				msg.setHead(rlines[0], rlines[1]);
			}
		}
		if (msg.getLength() > 0) {
			msg.setBody(this.read(msg.getLength()));
		}

		byte[] yz = this.read(4);

		if (Arrays.equals("-\r\n-".getBytes(), yz)) {
			return msg;
		} else {
			throw new MessageException(ExecStatus.MESSAGE_FORMAT_ERROR);
		}

	}

	private byte[] read(int len) throws IOException {
		byte[] data = new byte[len];
		int offset = 0;
		while (true) {
			offset = offset + mDataInputStream.read(data, offset, data.length - offset);
			if (offset == data.length) {
				break;
			}
		}
		return data;
	}

	@Override
	public int read() throws IOException {
		return mDataInputStream.read();
	}
}
